##线性回归
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import linear_model, discriminant_analysis
from DealData import load_data

def test_LinearRegression(*data):
    X_train, X_test, y_train, y_test,train,test= data
    #通过sklearn的linear_model创建线性回归对象
    linearRegression = linear_model.LinearRegression()
    #进行训练
    linearRegression.fit(X_train, y_train)
    #通过LinearRegression的coef_属性获得权重向量,intercept_获得b的值
    print("权重向量:%s, b的值为:%.2f" % (linearRegression.coef_, linearRegression.intercept_))
    #计算出损失函数的值
    print("损失函数的值: %.2f" % np.mean((linearRegression.predict(X_test) - y_test) ** 2))
    #计算预测性能得分
    print("预测性能得分: %.2f" % linearRegression.score(X_test, y_test))
    ##生成预测
    submission = pd.DataFrame()
    submission['Id'] = test.Id
    #根据上面所做的模型，从测试数据中选择特性
    feats = test.select_dtypes(
            include=[np.number]).drop(['Id'], axis=1).interpolate()
    #生成预测
    predictions = linearRegression.predict(feats)
    #预测转换成正确的形式，用np.exp()来做预测，因为之前已经取了对数。
    final_predictions = np.exp(predictions)
    submission['SalePrice'] = final_predictions
    #创建预测
    submission.to_csv('LinearRegressionPredictions.csv', index=False)



if __name__ == '__main__':
    #获得数据集
    X_train, X_test, y_train, y_test,train,test= load_data()
    #进行训练并且输出预测结果
    test_LinearRegression(X_train, X_test, y_train, y_test,train,test)
